#include "adc_val.h"
#include "main.h"
#include "adc.h"
#include "filter.h"
#include "motor_infor.h"
adc_origin_t adc_origin;
adc_transform_t adc_transform;
uint32_t adc_currunt_offset_ori[3][64];
float adc_currunt_offset_cal[3];
uint16_t adc_dma_data[3];
uint16_t adc_offset_flag = 0;
uint32_t count =0;

void read_adc(ADC_HandleTypeDef* adc1,ADC_HandleTypeDef* adc2,adc_origin_t* ori){

	ori->adc_A = adc1_filter_ia.out;
	ori->adc_B = adc1_filter_ib.out;
	ori->adc_C = adc1_filter_ic.out;
  if(count < 64){
    adc_currunt_offset_ori[0][count] = ori->adc_A;
    adc_currunt_offset_ori[1][count] = ori->adc_B;
    adc_currunt_offset_ori[2][count] = ori->adc_C;
    count++;
  }
  else if (count == 64){
    adc_offset_cal();
		    count++;	
  }
  else {
    cal_volatge_tran(ori,&adc_transform);
		calrk_func(&adc_transform,&REA_ialbe,&REA_iabc);
  }
	
	ori->adc_V_bus = adc_dma_data[0];
	
	
}
void adc_offset_cal(void){
  if(adc_offset_flag == 0){
    for(uint16_t i = 0 ;i <64;i++){
      adc_currunt_offset_cal[0]+=adc_currunt_offset_ori[0][i];
      adc_currunt_offset_cal[1]+=adc_currunt_offset_ori[1][i];
      adc_currunt_offset_cal[2]+=adc_currunt_offset_ori[2][i];
    }
    adc_currunt_offset_cal[0] = adc_currunt_offset_cal[0]/64.f;
    adc_currunt_offset_cal[1] = adc_currunt_offset_cal[1]/64.f;
    adc_currunt_offset_cal[2] = adc_currunt_offset_cal[2]/64.f;
  }
  adc_offset_flag = 1;
}

void cal_volatge_tran(adc_origin_t* ori,adc_transform_t* tra){
  if(adc_offset_flag == 1){
      tra->_cur_A = (ori->adc_A-2567.f )*3.3f/ADC_RAGNE*3.646f;
																										
      tra->_cur_B = (ori->adc_B-2558.f )*3.3f/ADC_RAGNE*3.646f;
																									
      tra->_cur_C = (ori->adc_C-2553.f )*3.3f/ADC_RAGNE*3.646f;

	  tra->voltage_BUS = ori->adc_V_bus*(18.f+169.f)/18.f*3.3f/4096.f;
  }
}

